extends GraphEdit

@onready var root = $root
@onready var treeNode = preload("res://components/block_tree/tree_node.tscn")

@export var x_offset = 150
@export var y_offset = 10
var lowest_position_y = 0

# Called when the node enters the scene tree for the first time.
func _ready():
	root.abEn.children_id.append('ddd')
	recontruct_tree()
	self.scroll_offset = Vector2(0,0)
	

func clear_tree():
	lowest_position_y = 0
	for child in get_children():
		if child == root:
			continue
		remove_child(child)
		child.queue_free()
	root.position_offset = Vector2(25,25)

# 创建树
func recontruct_tree():
	clear_tree()
	var level1_index = 0
	for ability_id in GlobalVariables.get_all_ability_keys():
		var ability_data = GlobalVariables.get_ability(ability_id)
		if ability_data.parent_id =='NULL':
			create_tree(root,ability_data,1,root.position_offset.y,level1_index)
			level1_index+=1
	
	root.position_offset = Vector2(25,int(25+(float(lowest_position_y)-25)/2))

#遍历整个树，创建树
func create_tree(node,ability_data:AbilityEntity,depth:int,parent_position_y:int,y_index:int):
	var child = treeNode.instantiate()
	child.abEn = ability_data
	add_child(child)
	# 当前节点是根据父节点位置进行设定
	var current_position_y = parent_position_y+y_index*y_offset
	if y_index>0 and current_position_y < lowest_position_y:
		current_position_y = lowest_position_y
	#print('parent:',parent_position_y,',current:',current_position_y,'index:',y_index)
	child.position_offset = Vector2(depth*x_offset+root.position_offset.x,current_position_y)
	lowest_position_y = lowest_position_y if lowest_position_y>current_position_y+y_offset else current_position_y+y_offset
	if len(ability_data.children_id)==0:
		connect_node(node.get_name(),0,child.get_name(),0)
		return child.position_offset.y
	else:
		depth+=1
		var level2_index = 0
		var children_y = []
		for subchild_id in ability_data.children_id:
			var subchild_data = GlobalVariables.get_ability(subchild_id)
			var sub_child_y = create_tree(child,subchild_data,depth,current_position_y,level2_index)
			level2_index +=1
			children_y.append(sub_child_y)
		child.position_offset = Vector2(child.position_offset.x,avg(children_y))
		connect_node(node.get_name(),0,child.get_name(),0)
		return child.position_offset.y
		
func avg(ys):
	var sum = 0
	for y in ys:
		sum += y
	return float(sum)/ys.size()

